﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NetPE.Dialogs
{
    public partial class FlagEnumDialog : BaseDialog
    {

        public FlagEnumDialog(object obj)
            : base(obj)
        {
            InitializeComponent();
            ulong val = GetValue(obj);
            string[] names = Enum.GetNames(obj.GetType());
            Array values = Enum.GetValues(obj.GetType());
            for (int i = 0; i < names.Length; i++)
            {
                checkedListBox1.Items.Add(names[i]);
                ulong mask = GetValue(values.GetValue(i));
                if ((val & mask) == mask)
                    checkedListBox1.SetItemChecked(i, true);
            }
            this.Text = obj.GetType().Name;
        }

        private ulong GetValue(object obj)
        {
            Type tmp = obj.GetType();
            if (tmp.BaseType.FullName == "System.Enum")
            {
                tmp = Enum.GetUnderlyingType(tmp);
            }
            switch (tmp.FullName)
            {
                case "System.Byte": return (byte)obj;
                case "System.UInt16": return (ushort)obj;
                case "System.UInt32": return (uint)obj;
                case "System.UInt64": return (ulong)obj;
                case "System.Int16": return (ulong)(short)obj;
                case "System.Int32": return (ulong)(int)obj;
                case "System.Int64": return (ulong)(long)obj;
            } throw new InvalidOperationException();
        }

        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (e.NewValue == CheckState.Checked)
            {
                ulong mask = GetValue(Enum.GetValues(Object.GetType()).GetValue(e.Index));
                ulong val = GetValue(Object);
                val = val | mask;
                this.Object = Enum.ToObject(Object.GetType(), val);
            }
            else if (e.NewValue == CheckState.Unchecked)
            {
                ulong mask = GetValue(Enum.GetValues(Object.GetType()).GetValue(e.Index));
                ulong val = GetValue(Object);
                val = val & ~mask;
                this.Object = Enum.ToObject(Object.GetType(), val);
            }
        }
    }
}
